﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudApiServer.Services
{
    /// <summary>
    /// 人员信息服务
    /// </summary>
    public class FsiPsnInfoService
    {
        /// <summary>
        /// 1101 查询人员信息
        /// </summary>
        /// <param name="fsiRequest">查询人员信息入参</param>
        /// <param name="CountrollerName">来源控制器名称</param>
        /// <returns>查询人员信息返参</returns>
        /// <exception cref="Exception"></exception>
        public async Task<outputQueryPsnInfo> QueryPsnInfo(FsiRequestHeader<InputQueryPsnInfoRequest> fsiRequest, string CountrollerName)
        {
            string cert_no = "";
            DataTable dt = new DataTable();
            string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
            //如果是从江苏医保且强制身份证有值 则取强制身份证的这个值
            if (!string.IsNullOrEmpty(FsiDatainfo.JiangsuDefautlcardno)&& CountrollerName == "FsiApiJiangsuJiangxiController")
            {
                cert_no = FsiDatainfo.JiangsuDefautlcardno;
            }
            else
            {
                //电子凭证的时候传certno 身份证号码
                if (fsiRequest.Input.data.mdtrt_cert_type == "01")
                {
                    cert_no = fsiRequest.Input.data.certno;
                }
                else
                {
                    //如果是身份证，且从浙江控制器传入，且区划为陕西，则通过入参分割获取身份证号
                    if (CountrollerName == "FsiApiZheJiangController" && fsiadmvs == "61" && fsiRequest.Input.data.mdtrt_cert_type == "03")
                    {
                        string[] parts = fsiRequest.Input.data.mdtrt_cert_no.Split('|');
                        cert_no = parts.Length > 4 ? parts[4] : null;
                    }
                    //如果是身份证，且从浙江控制器传入，且区划为浙江，从证件号码获取身份证号
                    else if (CountrollerName == "FsiApiZheJiangController" && fsiadmvs == "33" && fsiRequest.Input.data.mdtrt_cert_type == "03")
                    {
                        cert_no = fsiRequest.Input.data.certno;
                    }
                    else
                    {
                        cert_no = fsiRequest.Input.data.mdtrt_cert_no;
                    }
                }
            }
            //最后 如果拿到的证件号为空，则使用默认的证件号
            if (string.IsNullOrEmpty(cert_no))
            {
                cert_no = FsiDatainfo.Defautlcardno;
            }
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (var conn = new MySqlConnection(connectionString))
            {
                await conn.OpenAsync();
                using (MySqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "select * from fsi_PsnInfo where certno=@certno";
                    cmd.Parameters.AddWithValue("@certno", cert_no);
                    using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                    {
                        dt.Load(reader);
                        if (dt.Rows.Count == 1)
                        {
                            List<Idetinfo> list = new List<Idetinfo>();
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            var output = new outputQueryPsnInfo
                            {
                                baseinfo = new Baseinfo
                                {
                                    certno = dt.Rows[0]["certno"].ToString(),
                                    psn_no = dt.Rows[0]["psn_no"].ToString(),
                                    gend = dt.Rows[0]["gend"].ToString(),
                                    exp_content = dt.Rows[0]["exp_content"].ToString(),
                                    brdy = dt.Rows[0]["brdy"].ToString(),
                                    naty = dt.Rows[0]["naty"].ToString(),
                                    psn_cert_type = dt.Rows[0]["psn_cert_type"].ToString(),
                                    psn_name = dt.Rows[0]["psn_name"].ToString(),
                                    age = PublicMethod.CalculateAge(Convert.ToDateTime(dt.Rows[0]["brdy"]), dateTime),
                                    psn_mgtcode = dt.Rows[0]["psn_mgtcode"].ToString()
                                },
                                insuinfo = new List<Insuinfo>
                                        {
                                            new Insuinfo
                                            {
                                                insuplc_admdvs = dt.Rows[0]["insuplc_admdvs"].ToString(),
                                                psn_insu_date = dt.Rows[0]["psn_insu_date"].ToString(),
                                                cvlserv_flag = dt.Rows[0]["cvlserv_flag"].ToString(),
                                                balc = Convert.ToDouble(dt.Rows[0]["balc"]),
                                                emp_name = dt.Rows[0]["emp_name"].ToString(),
                                                psn_type = dt.Rows[0]["psn_type"].ToString(),
                                                psn_insu_stas = dt.Rows[0]["psn_insu_stas"].ToString(),
                                                insutype = dt.Rows[0]["insutype"].ToString(),
                                                paus_insu_date = dt.Rows[0]["paus_insu_date"].ToString()
                                            }
                                        },
                                idetinfo = new List<Idetinfo>
                                        {
                                            new Idetinfo
                                            {
                                                psn_idet_type = dt.Rows[0]["psn_idet_type"].ToString(),
                                                psn_type_lv =dt.Rows[0]["psn_type_lv"].ToString(),
                                                memo=dt.Rows[0]["memo"].ToString(),
                                                begntime =dt.Rows[0]["begntime"].ToString(),
                                                endtime = dt.Rows[0]["endtime"].ToString(),
                                            }
                                        }
                            };
                            return output;
                        }
                        else
                        {
                            throw new Exception($"查询人员信息表失败！根据传入的证件号【{cert_no}】查询到的人员信息总数为：{dt.Rows.Count}");
                        }
                    }
                }
            }
        }
    }
}
